import {Table, Menu, Dropdown, Icon, Button, Transfer, Modal, Spin, Pagination, Popover} from 'antd';
// import Table from '../../_antd1.11.2/table'
// import Menu from '../../_antd1.11.2/menu'
// import Dropdown from '../../_antd1.11.2/dropdown'
// import Icon from '../../_antd1.11.2/icon'
// import Button from '../../_antd1.11.2/button'
// import Transfer from '../../_antd1.11.2/transfer'
// import Modal from '../../_antd1.11.2/modal'
// import Spin from '../../_antd1.11.2/spin'
// import Pagination from '../../_antd1.11.2/pagination';

import cloneDeep from 'lodash/cloneDeep'
// import Popover from '../../_antd1.11.2/popover';
import WeaDocsThumbnails from '../base/wea-docs-thumbnails'
const MenuItem = Menu.Item;

import "./style/index.js";
//国际化 zxt- 20170419
const defaultLocale = {
  	total: '共',
  	totalUnit: '条',
  	operates: '操作',
  	customColTitle: '定制列',
  	customColSelect: '待选列名',
  	customColSelected: '已选列名',
  	customColSave: '保存',
  	customColCancel: '取消',
};

class WeaTable extends React.Component {
	//国际化 zxt- 20170419
	static contextTypes = {
	    antLocale: React.PropTypes.object,
	}
	getLocale() {
	    let locale = {};
	    if (this.context.antLocale && this.context.antLocale.Table) {
	    	locale = this.context.antLocale.WeaTable;
	    }
	    return { ...defaultLocale, ...locale, ...this.props.locale };
  	}
	constructor(props) {
        super(props);
        this.state = {
            height:0,
            filters: {},
            sorter: {},
            pagination: {},
        }
    }
	scrollheigth(h = 0){
		const {heightSpace} =  this.props;
		let heightOther = heightSpace || 0;
        if(jQuery(".wea-new-table") && jQuery(".wea-new-table .ant-pagination.ant-table-pagination")){
			let widowClientHeight = document.documentElement.clientHeight || 0;
			let top = jQuery(".wea-new-table").offset() ? jQuery(".wea-new-table").offset().top : 0;
			let titileHeight = jQuery(".wea-new-table .ant-table-header .ant-table-thead").height() || 45;
			let bottom = (jQuery(".wea-new-table .ant-pagination.ant-table-pagination").height() || 30 ) + 15;
	        let scrollheigth = widowClientHeight - top - titileHeight - bottom;
	        this.setState({
		        height: scrollheigth - 15 - heightOther - h
		    })
		}
	}
	componentWillReceiveProps(nextProps){
		if((!this.props.columns || !this.props.columns.length == 0) && nextProps.columns){
			this.scrollheigth();
		}
	}
	componentDidUpdate(){
		if(!this.props.pageAutoWrap){
			jQuery('.wea-new-table table').css({width:'100%',tableLayout:'fixed'})
	        jQuery('.wea-new-table table td').find('div').css({overflow:'hidden',whiteSpace:'nowrap',textOverflow:'ellipsis',width:'100%',display:'inline-block',verticalAlign: 'middle'});
	        jQuery('.wea-new-table table td').find('a').css({overflow:'hidden',whiteSpace:'nowrap',textOverflow:'ellipsis',maxWidth:'90%',display:'inline-block',verticalAlign: 'middle'})
			jQuery('.wea-new-table table td').find('a').map((i,a)=>{a.title = a.innerText})
	        jQuery('.wea-new-table table td').find('.wea-url').map((i,d)=>{d.title = d.innerText})
		}
		if(this.props.pageAutoWrap){
	        jQuery('.wea-new-table table').css({tableLayout:'inherit'})
	        jQuery('.wea-new-table table td').find('div').css({overflow:'inherit',whiteSpace:'normal',textOverflow:'inherit'});
	        jQuery('.wea-new-table table td').find('a').css({overflow:'inherit',whiteSpace:'normal',textOverflow:'inherit'})
		}
	}
	componentDidMount(){
        this.scrollheigth(35);
        const {pageAutoWrap} = this.props;
        this.componentDidUpdate();
        jQuery(window).resize(() => {
		    this._reactInternalInstance !== undefined && this.scrollheigth()
		});
    }
    render() {
        const {columns,datas,browser,rowSel,loading,operates,tableCheck,heightSpace,needScroll,noOperate,sortParams,hasOrder,
        	colSetVisible,colSetdatas,colSetKeys,pageAutoWrap, fixedPagination = false, showThumbnails = false, pagination} = this.props;
        const {height} = this.state;
        const locale = this.getLocale();
        let newColumns = cloneDeep(columns);
        let oldWidthObj = {}
        let num = 0;
        let nowWidth = 0;
        let scrollHeight = needScroll ? {scroll:{ y:height }} : {};
        newColumns = newColumns.filter((newColumn)=>{
            if(newColumn.display==="true") {
                const width = newColumn.oldWidth?parseFloat(newColumn.oldWidth.substring(0,newColumn.oldWidth.length-1)):10;
                oldWidthObj[newColumn.dataIndex] = width;
                num++;
                nowWidth+=width;
            }
            return newColumn.display==="true";
        });
        !noOperate && datas && newColumns && datas.length > 0 && newColumns.length > 0 && operates && operates.length>0 && newColumns.push({
            title:"",
            dataIndex:"randomFieldOperate",
            key:"randomFieldOperate",
            className:"wea-table-operates",
            render: (text,record,index)=> {
                const rfs = record.randomFieldOp ? typeof(record.randomFieldOp) == 'object' ? record.randomFieldOp : JSON.parse(record.randomFieldOp):{};
                let argumentString = [];
                !!record.randomFieldOpPara && record.randomFieldOpPara.map(r=>{argumentString.push(r.obj)})

                let showOperate = null;
                let shouFn = null;
                let hiddenOperate = new Array();
                let opNum = 0;
                operates.map((operate,index)=>{
                    let flag = operate.index || "-1";
                    if(rfs[flag]&&rfs[flag]!="false") opNum++;

                    let fn = '';
                    if(operate.href){
                    	fn = operate.href.split(':')[1].split(')')[0];
                    	if(typeof record.randomFieldId === 'number')
                    		fn += record.randomFieldId;
                    	if(typeof record.randomFieldId === 'string')
                    		fn += '"' + record.randomFieldId + '"';
                    	if(argumentString.length && argumentString.length > 0){
                    		fn += ',';
                    		argumentString.map(a => {
                    			if(typeof record.randomFieldId === 'number')
		                    		fn += a;
		                    	if(typeof record.randomFieldId === 'string')
		                    		fn += '"' + a + '"';
                    		})
                    	}
                    	fn += ')';
                    }

                    //let fn = operate.href ? `${operate.href.split(':')[1].split(')')[0]}${record.randomFieldId}${argumentString.length?',"':''}${argumentString}${argumentString.length?',"':''});` : ""
                    // if(opNum==1&&rfs[flag]&&rfs[flag]!="false") {
                    //     showOperate = operate;
                    //     shouFn = fn;
                    // }
                    //{showOperate && <a href="javascript:void(0);" onClick={()=>{eval(shouFn)}} style={{marginRight:5}}>{showOperate.text}</a>}
                    if(rfs[flag]&&rfs[flag]!="false") {
                        hiddenOperate.push(
                            <MenuItem key={index}>
                                <a href='javascript:void(0);' onClick={()=>{
                                        typeof this.props.onOperatesClick === 'function' ? this.props.onOperatesClick(record,index,operate,flag) : eval(fn)
                                    }
                                }>{operate.text}</a>
                            </MenuItem>
                        );
                    }
                });
                const menu = (
                    <Menu>
                        {hiddenOperate}
                    </Menu>
                )
                return (
                    <div>
                        {hiddenOperate.length>0 &&
                        (<Dropdown overlay={menu}>
                            <a className="ant-dropdown-link" href="javascript:void(0);">
                                {locale.operates} <Icon type="caret-down" />
                            </a>
                        </Dropdown>)}
                    </div>
                )
            }
        });
        newColumns = newColumns.map((newColumn)=>{
            if(newColumn.display==="true") {
                newColumn.width = (
                    parseFloat(oldWidthObj[newColumn.dataIndex])+
                    (100-nowWidth)*parseFloat(oldWidthObj[newColumn.dataIndex]/nowWidth)
                )+"%";
                if(hasOrder && newColumn.orderkey) {
                	newColumn.sorter = true;
                	if(sortParams && sortParams.length > 0){
	                	sortParams.map(s=>{
	                		if(s.orderkey == newColumn.orderkey)
		                	newColumn.sortOrder = s.sortOrder;
	                	});
                	}else{
                		newColumn.sortOrder = false;
                	}
                }
                return newColumn;
            }
            return newColumn;
        });
        const newRowSel = tableCheck?{
            ...rowSel,
            getCheckboxProps: (record) => {
                return {disabled: record["randomFieldCk"] !== "true"};
            }
        }:null;
//      const autoWrap = pageAutoWrap ? {} :
//      	{
//      		whiteSpace: 'nowrap',
//				overflow: 'hidden',
//				textOverflow: 'ellipsis'
//			};
        return (
            <div className="wea-new-table" >
            	<div style={{width: '100%',height: '100%'}}>
            		<div style={showThumbnails ? {width: '100%', height: height + 45} : {width: '100%'}}>
		                { showThumbnails ?
		                	<WeaDocsThumbnails  {...this.props} height={height + 45}/>
		                	:
		                	<Table
                                {...this.props}
                                {...scrollHeight}
                                loading={false}
			                	rowSelection={newRowSel}
			                	columns={newColumns}
			                	needWeaLoading={true}
			                	loadingWea={loading}
			                	dataSource={newColumns && newColumns.length > 0 ? datas : []}
			                	pagination={false}
			                	rowKey={record => record.randomFieldId}
			                	onRowClick={this.onRowClick.bind(this)}
			                	onChange={this.onChange.bind(this)}
		                	/>
		                }
	                </div>
                    {pagination &&
                        <div className='wea-table-pagination' style={showThumbnails ? { borderTop: '1px solid #d6d6d6', position: 'absolute' ,bottom: 0, right: 0} : {}}>
                            <Pagination
                                className='ant-table-pagination'
                                {...this.getPagination()}
                            />
                        </div>
                    }
                </div>
                <Modal visible={colSetVisible}
                	title={locale.customColTitle}
                	className='wea-table-colset-modal'
                	onCancel={this.showColumnsSet.bind(this,false)}
                	footer={<div style={{width:'100%',textAlign:'center',paddingLeft:8}}>
                		<Button type="primary" onClick={()=>{if(typeof this.props.saveColumnsSet == "function"){this.props.saveColumnsSet()}}} >{locale.customColSave}</Button>
                		<Button type="ghost" onClick={this.showColumnsSet.bind(this,false)} >{locale.customColCancel}</Button>
                	</div>}>
                	<Spin spinning={loading}>
                		<Transfer className='wea-table-colset'
	                		dataSource={colSetKeys && colSetdatas}
	                		targetKeys={colSetKeys}
	                		titles={[locale.customColSelect,locale.customColSelected]}
	                		listStyle={{
					            width: 220,
					            height: 300,
					        }}
	                		render={o =>{return <span style={{display:'inline-block',minWidth:'80%'}} value={o.name} onDoubleClick ={this.onLiDoubleClick.bind(this,o)}>{o.name}</span>}}
	                		onChange={(targetKeys, direction, moveKeys)=>{if(typeof this.props.onTransferChange == "function"){this.props.onTransferChange(targetKeys, direction, moveKeys)}}}
	                		/>
                	</Spin>
                </Modal>
            </div>
        )
    }
    onChange(pagination, filters, sorter){
      	const { onChange } = this.props;
      	this.setState({filters, sorter}, () => {
      		const { pagination, filters, sorter } = this.state;
      		typeof onChange == "function" && onChange(pagination, filters, sorter)
      	})
    }
    showColumnsSet(bool){
    	if(typeof this.props.showColumnsSet == "function"){
    		this.props.showColumnsSet(bool)
		}
    }
    onLiDoubleClick(o){
    	const {colSetKeys} = this.props;
    	let newKeys = colSetKeys.indexOf(o.key) >= 0 ? colSetKeys.filter(c =>{return c !== o.key}) : [o.key].concat(colSetKeys);
    	if(typeof this.props.onTransferChange == "function"){
    		this.props.onTransferChange(newKeys, '', [o.key])
    	}
    }
    onRowClick(record,index){
    	if(typeof this.props.onRowClick === 'function'){this.props.onRowClick(record,index)}
    }
    getPagination() {
        const {count,current,size,pageSize} = this.props;
        const locale = this.getLocale();
        let that = this;
        let obj = {
        	size: size ? size : {},
            total:count,
            showTotal(total) {
                return `${locale.total} ${total} ${locale.totalUnit}`;
            },
            showSizeChanger: true,
            showQuickJumper: true,
            pageSizeOptions: [10,20,50,100],
            onShowSizeChange: (current, pageSize) => {
            	let { pagination } = this.state,
            		{ onChange } = this.props;
            	pagination.current = current;
            	pagination.pageSize = pageSize;
		      	this.setState({ pagination }, () => {
		      		let { pagination, filters, sorter } = this.state;
		      		typeof onChange == "function" && onChange(pagination, filters, sorter)
		      	})
            },
            onChange: current => {
            	let { pagination } = this.state,
            		{ onChange } = this.props;
            	pagination.current = current;
            	this.setState({ pagination }, () => {
		      		let { pagination, filters, sorter } = this.state;
		      		typeof onChange == "function" && onChange(pagination, filters, sorter)
		      	})
            },
        };
        if(typeof pageSize !== 'undefined'){
        	obj.pageSize = pageSize
        }
        if(typeof current !== 'undefined'){
        	obj.current = current
        }
        return obj
    }
}

WeaTable.defaultProps = {
    pagination: true
};
WeaTable.propTypes = {
    pagination: React.PropTypes.bool//是否有翻页，默认为true
};
// if (window.ecCom) {
//     window.ecCom.WeaTable = WeaTable;
// } else {
//     console.error("无法取到ecCom");
// }
export default WeaTable;